
var prefix = ctx +"module/device"
$(function() {
    load();
    getTemperatureRecordData(0);
    setInterval(function(){
        reLoad(); // 重载当前页面
        getTemperatureRecordData(0);
    },120000); // 参数为刷新间隔（单位为毫秒），这里表示每1分钟刷新一次
});
function load(){
    layui.use(['form','table'], function() {
        var form = layui.form , table = layui.table,element = layui.element;//载入table模块
        var searchParams = {};
        searchParams['search_like_keyword']=$('#keyword').val();
        // searchParams['search_eq_deviceType']=$('#deviceType').val();
        searchParams['search_eq_shopId']=$('#shopId').val();
        searchParams['search_eq_positionType']=$('#positionType').val();

        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/list",//请求数据连接
            toolbar: '#toolbarDemo',
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            // height: 'full-75',
            where :{
                searchParams:searchParams,
                sorts:{"id":"desc"}
            },
            defaultToolbar: false,
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
            },
            cols: [[
                {type:'numbers',title: '序号', width:'5%'},
                { field : 'deviceName',  title : '设备名称', align : 'center', },
                { field : 'deviceNum',  title : '设备编号', align : 'center',width:100, },
                { field : 'shopName',  title : '所属企业', align : 'center',},
                { field : 'deviceType',  title : '设备类型', align : 'center', width:200,
                    templet: function (item) {
                        if (item.deviceType == 2) {
                            return '<span class="label label-success">测高温</span>';
                        } else if (item.deviceType == 3) {
                            return '<span class="label label-success">测高温+测电流</span>';
                        } else if (item.deviceType == 4)  {
                            return '<span class="label label-success ">测高温+测电流+测电压</span>';
                        }
                    },
                },
                // { field : 'leaderName',  title : '负责人', align : 'center', },
                // { field : 'leaderPhone',  title : '负责人电话', align : 'center', },
                // { field : 'sort',  title : '排序索引', align : 'center', width: 80 },
                { field : 'currentValue',  title : '当前数据', align : 'center', width: 320,
                    templet: function (item) {
                        let str = '<span style="font-size:20px;">';
                        let nodeList = item.nodeList;
                        for (let index in nodeList){
                            str += nodeList[index].terminalName + ' ： ' + nodeList[index].currentValue + ' ; ';
                        }
                        str += '</span>'
                        return str;
                    },
                },
                // { field : 'address',  title : '设备位置', align : 'center', },
                { title: '操作', minWidth: 320, templet: '#currentTableBar', fixed: "right", align: "center"}
            ]],
            id: 'currentTableId'//表格Id
        });
        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {  // 监听添加操作
                console.log('obj',obj.data.id)
                edit(obj.data.id);
            } else if (obj.event === 'delete') {  // 监听删除操作
                console.log('obj',obj.data.id)
                remove(obj.data.id);
            } else if (obj.event === 'charts') {  // 监听删除操作
                console.log('obj',obj.data.id);
                goCharts(obj.data.id);
            } else if (obj.event === 'nodes') {  // 监听删除操作
                console.log('obj',obj.data.id);
                goNodes(obj.data.id);
            }

        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            reLoad();
            return false;
        });

        /**
         * 操作栏tool  监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                add();
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            } else if(obj.event === 'back'){
                goBack();
            }
        });
    });
}

function reLoad() {
    var searchParams = {};
    searchParams['search_like_keyword']=$('#keyword').val();
    // searchParams['search_eq_deviceType']=$('#deviceType').val();
    searchParams['search_eq_shopId']=$('#shopId').val();
    searchParams['search_eq_positionType']=$('#positionType').val();
    layui.use(['table'], function() {
        var  page = $(".layui-laypage-skip").find("input").val() //当前页码值
        console.log('page',page)
        var table = layui.table;//载入table模块
        table.reload('currentTableId', {
            page: {curr: page}
            , where: {
                searchParams: searchParams
            }
        }, 'data');
    });
}

/**
 * 获取设备的统计
 */
function getTemperatureRecordData(type) {
    var url = ctx + "module/device/shop/device/charts/data";
    $.ajax({
        cache : true,
        type : "POST",
        url : url,
        data:{
            shopId: $("#shopId").val(),
            shopType: $("#shopType").val(),
            positionType: $("#positionType").val(),
            dateType: type,
        },
        async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            console.log('data',data);
            let all_data_2 = data.all_data_2;
            let all_data_3 = data.all_data_3;

            if(all_data_2.dataList != undefined && all_data_2.dataList.length > 0){
                reloadTempData2(all_data_2);
            }

            console.log('all_data_3',all_data_3)
            console.log('all_data_3.length',all_data_3.length)
            if(all_data_3.dataList != undefined && all_data_3.dataList.length > 0){
                reloadDianLiuData(all_data_3);
            }
        }
    });
}



function reloadTempData(data){

    var times = data.dataList[0].times;

    var legend = data.deviceNames;

    var series = [];
    for (let index in data.dataList){
        var values = data.dataList[index].values;

        for(let i in  values){
            let value = values[i];
            if(value == "" || value == "null"){
                values[i] = null;
            }
        }
        console.log("values", values);
        let serie = {
            type:'line',
            name: legend[index],
            data: values,
            smooth: true // 可选，使线条平滑
            // itemStyle: {
            //     normal: {
            //         label: {
            //             show: true, //开启显示
            //             position: 'top', //在上方显示
            //             textStyle: { //数值样式
            //                 color: 'blue',
            //                 fontSize: 16
            //             }
            //         }
            //     }
            // },
        };
        series.push(serie);
    }


    var lineChart = echarts.init(document.getElementById("echarts-line-chart-wendu"));
    var lineoption = {
        tooltip : {
            trigger: 'axis',
            show : true
        },
        legend: {
            data: legend
        },
        grid:{
            x:30,y:30,x2:5
        },
        calculable : false,
        xAxis : {
            type: 'category',
            data: times,
        },
        yAxis : [
            {
                type : 'value',
                // max:100,
                axisLabel : {
                    formatter: '{value}'
                }
            }
        ],
        series : series,
    };
    lineChart.setOption(lineoption);
    $(window).resize(lineChart.resize);
}

// 单个一条线
function reloadTempData2(data){
    for (let index in data.dataList){
        document.getElementById("echart"+index).style.display="";
        var times = data.dataList[index].times;

        var legendstr =  data.deviceNames[index]
        var legends =  []
        legends.push(data.deviceNames[index])
        var values = data.dataList[index].values;
        for(let i in  values){
            let value = values[i];
            if(value == "" || value == "null"){
                values[i] = null;
            }
        }
        var series = [];
        let serie = {
            type:'line',
            name: legendstr,
            data: values,
            smooth: true // 可选，使线条平滑
            // itemStyle: {
            //     normal: {
            //         label: {
            //             show: true, //开启显示
            //             position: 'top', //在上方显示
            //             textStyle: { //数值样式
            //                 color: 'blue',
            //                 fontSize: 16
            //             }
            //         }
            //     }
            // },
        };
        series.push(serie);

        var lineChart = echarts.init(document.getElementById("echarts-line-chart-wendu"+index));
        var lineoption = {
            tooltip : {
                trigger: 'axis',
                show : true
            },
            legend: {
                data: legends
            },
            grid:{
                x:30,y:30,x2:5
            },
            calculable : true,
            xAxis : {
                type: 'category',
                data: times,
                boundaryGap: false,
            },
            yAxis : [
                {
                    type : 'value',
                    max:100,
                    axisLabel : {
                        formatter: '{value}'
                    }
                }
            ],
            series : series,
        };
        lineChart.setOption(lineoption);
        $(window).resize(lineChart.resize);
    }
}




function reloadDianLiuData(data){

    var times = data.dataList[0].times;

    var legend = data.deviceNames;

    var series = [];
    for (let index in data.dataList){
        var values = data.dataList[index].values;

        for(let i in  values){
            let value = values[i];
            if(value == "" || value == "null"){
                values[i] = null;
            }
        }
        console.log("values", values);
        let serie = {
            type:'line',
            name: legend[index],
            data: values,
            smooth: true // 可选，使线条平滑
            // itemStyle: {
            //     normal: {
            //         label: {
            //             show: true, //开启显示
            //             position: 'top', //在上方显示
            //             textStyle: { //数值样式
            //                 color: 'blue',
            //                 fontSize: 16
            //             }
            //         }
            //     }
            // },
        };
        series.push(serie);
    }


    var lineChart = echarts.init(document.getElementById("echarts-line-chart-dianliu"));
    var lineoption = {
        tooltip : {
            trigger: 'axis',
            show : true
        },
        legend: {
            data: legend
        },
        grid:{
            x:30,y:30,x2:5
        },
        // calculable : true,
        xAxis : {
            type: 'category',
            data: times,
        },
        yAxis : [
            {
                type : 'value',
                axisLabel : {
                    formatter: '{value}'
                }
            }
        ],
        series : series,
    };
    lineChart.setOption(lineoption);
    $(window).resize(lineChart.resize);
}



/**
 * 获取设备的统计
 */
function getDianLiuRecordData(type) {
    var url = ctx + "module/device/shop/device/charts/data";
    $.ajax({
        cache : true,
        type : "POST",
        url : url,
        data:{
            shopId: $("#shopId").val(),
            shopType: $("#shopType").val(),
            positionType: $("#positionType").val(),
            dateType: type,
        },
        async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            console.log('data',data);
            var times = data.times;
            var values = data.values;
            // var values1 = data.values1;

            $("#begin_date").val(data.beginDate);
            $("#end_date").val(data.endDate);

            var lineChart = echarts.init(document.getElementById("echarts-line-chart-dianliu"));
            var lineoption = {
                tooltip : {
                    trigger: 'axis',
                    show : true
                },
                grid:{
                    x:30,y:30,x2:5
                },
                // calculable : true,
                xAxis : {
                    type: 'category',
                    data: times,
                },
                yAxis : [
                    {
                        type : 'value',
                        axisLabel : {
                            formatter: '{value}'
                        }
                    }
                ],
                series :
                    {
                        type:'line',
                        name: '温度',
                        data:values,
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true, //开启显示
                                    position: 'top', //在上方显示
                                    textStyle: { //数值样式
                                        color: 'blue',
                                        fontSize: 16
                                    }
                                }
                            }
                        },
                    },
            };
            lineChart.setOption(lineoption);
            $(window).resize(lineChart.resize);
        }
    });
}


function goBack(){
    // var shopType = $('#shopType').val();
    // window.location.href = ctx + 'module/device/'+shopType;
    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    parent.layer.close(index);
}

function add() {
    // var deviceType = $("#deviceType").val();
    var shopId = $('#shopId').val();
	var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '550px' ],
        content : prefix + '/add/' + shopId // iframe的url
    });
	// layer.full(index);
}

function goNodes(id) {
    var index = layer.open({
        type : 2,
        title : '设备节点',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '780px' ],
        content : prefix + '/node/' + id // iframe的url
    });
    layer.full(index);
}

function goCharts(id) {
    var index = layer.open({
        type : 2,
        title : '高温设备监控',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '550px' ],
        content : prefix + '/charts/' + id // iframe的url
    });
    layer.full(index);
}

function edit(id) {
	var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '550px' ],
        content : prefix + '/edit/' + id // iframe的url
    });
	// layer.full(index);
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}


